package com.springcloud.sc.ucpv5.client.commondata;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.springcloud.sc.ucpv5.client.application.message.DataMessageManager;
import com.springcloud.sc.ucpv5.client.commondata.data.Group;
import com.springcloud.sc.ucpv5.client.commondata.data.GroupDataInfo;
import com.springcloud.sc.ucpv5.client.commondata.data.StatusStruct;
import com.springcloud.sc.ucpv5.client.contentmain.MainConstant;

import com.springcloud.sc.ucpv5.client.module.datamanager.BaseDataManager;
import com.springcloud.sc.ucpv5.client.module.datamanager.LoginDataManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



public class MyGroup extends ModelBase {

	private static final Logger logger = LoggerFactory.getLogger(MyGroup.class);

	protected Group idlData;

	protected StatusStruct statusStruct = new StatusStruct();;


	protected String physicsNodeNumber = "";

	protected String logicNodeNumber = "";

	protected int treeLevel = 0;


	public int getPriority() {
		return idlData.Priority;
	}

	public GroupDataInfo getGroupDataInfo() {
		return idlData.groupDataInfo;
	}

	public boolean isTopGroup() {
		return "".equalsIgnoreCase(idlData.ParGrpTelno);
	}

	// 20140625 根据话单生成的节点,建立的节点组
	public static String 节点组分隔标志 = "151413";

	public static String[] 临时组分隔标志列表 = new String[] { "*", "131415" };
	public static String 临时组分隔标志 = "131415";
	public static String 临时会话组分隔标志 = "**";

	public boolean isTmpGroup() {
		if (getIdlData().GroupType == 1) {
			return true;
		}

		for (String 临时组分隔标志 : 临时组分隔标志列表) {
			// 带*号的号码为临时组
			String groupNum = idlData.GroupTelno;
			if ((groupNum.lastIndexOf(临时组分隔标志) >= 0) && (groupNum.lastIndexOf(临时组分隔标志) + 临时组分隔标志.length() + 1) == groupNum.length()) {
				return true;
			} else {
				// 临时会话组也放到临时组内
				if (isNeedDelGroup()) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 是否自身临时组
	 * 
	 * @return
	 */
	public boolean isTmpOwnGroup() {
		try {
			for (String 临时组分隔标志 : 临时组分隔标志列表) {

				// 带*号的号码为临时组
				String groupNum = idlData.GroupTelno;

				if (groupNum.lastIndexOf(临时组分隔标志) < 0) {
					continue;
				}

				String number = groupNum.substring(0, groupNum.lastIndexOf(临时组分隔标志));

				if (number.equals(LoginDataManager.getInstance().getUserTelphone())) {
					return true;
				}
			}

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return false;

		// String user = CurrentUserObj.getInstance().getUserTelphone();
		// if(idlData.GroupTelno.startsWith(user)){
		// return true;
		// }
		//
		// return false;
	}

	/**
	 * 是否自身临时组
	 * 
	 * @return
	 */
	public String TmpGroup_User() {
		try {
			for (String 临时组分隔标志 : 临时组分隔标志列表) {
				// 带*号的号码为临时组
				String groupNum = idlData.GroupTelno;

				if (groupNum.lastIndexOf(临时组分隔标志) < 0) {
					continue;
				}
				String number = groupNum.substring(0, groupNum.lastIndexOf(临时组分隔标志));

				return number;
			}

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}

	private void clear() {
		baseListModel.clear();
	}

	synchronized void dispose() {
		clear();
	}

	public boolean equals(Object tmp) {
		if (!(tmp instanceof MyGroup)) {
			return false;
		}

		MyGroup user = (MyGroup) tmp;
		if (getKey().equals(user.getKey())) {
			return true;
		}

		return false;
	}

	public int hashCode() {
		return this.getKey().hashCode() << 8;
	}

	public MyGroup(Group groupData, String nodeNumber, String logicNodeNumber, int flag) {
		setIdlData(groupData);
		this.physicsNodeNumber = nodeNumber;
		this.logicNodeNumber = logicNodeNumber;

		// 初始组状态为空闲
		statusStruct.status = MainConstant.Status_GROUP_USER_STATUS_IDLE;

		BaseDataManager.getInstance().groupAdd(this);
	}

	public int getStatus() {
		return statusStruct.status;
	}

	public boolean setStatus(StatusStruct status) {
		if (status == null || status.status == this.statusStruct.status)
			return false;
		this.statusStruct = status;

		return true;
	}

	public String getKey() {
		return idlData.GroupTelno;
	}

	public String getTelno() {
		return idlData.GroupTelno;
	}

	public String getLabel() {
		StringBuffer buffer = new StringBuffer();
		buffer.append(idlData.GroupName);
		buffer.append("[");
		buffer.append(idlData.GroupTelno);
		buffer.append("]");

		buffer.append("(");
		buffer.append(getListModel().getUserOwnOnLineTotal());
		buffer.append("/");
		buffer.append(getListModel().getUserOwnTotal());
		buffer.append(")");

		return buffer.toString();
	}

	public String getOnLineUserSizeLabel() {
		try {
			StringBuffer buffer = new StringBuffer();
			buffer.append("(");
			buffer.append(getListModel().getUserOwnOnLineTotal());
			buffer.append("/");
			buffer.append(getListModel().getUserOwnTotal());
			buffer.append(")");

			return buffer.toString();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return "";
	}

	private String getStatusDesc() {
		switch (statusStruct.status) {
		case MainConstant.Status_GROUP_USER_STATUS_LISTENING:
			return MainConstant.ICON_EXT_GROUP_calling;
		case MainConstant.Status_GROUP_USER_STATUS_TALKING:
			return MainConstant.ICON_EXT_GROUP_calling;
		case MainConstant.Status_GROUP_USER_STATUS_TEL_BUSY:
			return MainConstant.ICON_EXT_GROUP_calling;
		case MainConstant.Status_GROUP_USER_STATUS_IDLE:
			return MainConstant.ICON_EXT_GROUP_online;
		case MainConstant.Status_GROUP_USER_STATUS_LOGOUT:
			return MainConstant.ICON_EXT_GROUP_offline;
		case MainConstant.Status_GROUP_USER_STATUS_UNREACH:
			return MainConstant.ICON_EXT_GROUP_offline;
		case MainConstant.Status_GROUP_USER_STATUS_NOT_EXIST:
			return MainConstant.ICON_EXT_GROUP_offline;
		case MainConstant.Status_GROUP_USER_STATUS_METTING:
			return MainConstant.ICON_EXT_GROUP_metting;
		case MainConstant.Status_GROUP_USER_STATUS_CALLING:
			return MainConstant.ICON_EXT_GROUP_calling;
		default:
			return MainConstant.ICON_EXT_GROUP_online;
		}
	}

	public String getIconDesc() {
		String status = getStatusDesc();

		String UserIconName = idlData.IconName;
		if ("".equals(UserIconName)) {
			UserIconName = "O_Group_0_online.png";
		}

		int index = UserIconName.lastIndexOf("_");
		return UserIconName.substring(0, index) + "_" + status + ".png";
	}

	public String getIconDesc(String status) {
		String UserIconName = idlData.IconName;
		if ("".equals(UserIconName)) {
			UserIconName = "O_Group_0_online.png";
		}

		int index = UserIconName.lastIndexOf("_");
		return "Legend.type.CustomGroupHead." + UserIconName.substring(0, index) + "_" + status;
	}

	public void invokeAction(int actionId) {
	}

	public String getStatusLabel() {
		String str = getStatusStr();
		return str != null ? "(" + str + ")" : null;
	}

	public String getStatusStr() {
		String key = Integer.toHexString(statusStruct.status);
		if (key.length() < 2)
			key = "Status_GROUP_USER_STATUS_0X0" + key;
		else
			key = "Status_GROUP_USER_STATUS_0X" + key;

		String desc = key;

		if (desc.startsWith("Status_GROUP_USER_STATUS_0X")) {
			// 不认识的当空闲组处理
			// 未知状态
			// desc = DcsMainUtil.getStrRes("Status_GROUP_USER_STATUS_0X10");

			if (statusStruct.status != 0) {
				StringBuffer buffer = new StringBuffer();
				buffer.append(desc);
				buffer.append("(");
				buffer.append(statusStruct.status);
				buffer.append(")");

				return buffer.toString();
			} else
				return desc;
		} else
			return desc;
	}

	public String getFieldText(int fieldId) {
		switch (fieldId) {
		case MainConstant.FIELD_TYPE_NAME:
			return idlData.GroupName;
		case MainConstant.FIELD_TYPE_ParentNumber:
			return idlData.ParGrpTelno;
		case MainConstant.FIELD_TYPE_Status:
		case MainConstant.FIELD_TYPE_DEFAULT_SEC_LABEL:
			return (getStatusStr() != null ? getStatusStr() : "");
		case MainConstant.FIELD_TYPE_USER_NUM:
			return "" + baseListModel.getTotalSize();
		case MainConstant.FIELD_TYPE_GCallTimer:
			return idlData.GCallTimer + "";
		case MainConstant.FIELD_TYPE_FreeTimer:
			return idlData.FreeTimer + "";
		case MainConstant.FIELD_TYPE_LETimer:
			return idlData.LETime + "";
		case MainConstant.FIELD_TYPE_TALK_PEER_TEL:
			return "";
		case MainConstant.FIELD_TYPE_IP:
		case MainConstant.FIELD_TYPE_MULI_IP:
			return idlData.ip;
		case MainConstant.FIELD_TYPE_Port:
			return idlData.port + "";
		case MainConstant.FIELD_TYPE_TEL:
			return idlData.GroupTelno + "";
		}

		return "--";
	}

	public int getIdField(int fieldId) {
		return MainConstant.FIELD_TYPE_ID;
	}

	public int getSortLevel() {
		if (isTmpGroup()) {
			// System.out.println("组SortLevel:" + getIdlData().GroupName + ":" +
			// treeLevel + 2001);
			// 20131120 在做临时组建立时,树上显示所有的组,那么,将临时组放到最后, 之前是组level都是2000
			return treeLevel + 2001;
		}

		// System.out.println("组SortLevel:" + getIdlData().GroupName + ":" +
		// (treeLevel + 2000));
		return treeLevel + 2000;
	}

	public String getSortLabel(int fieldId) {
		switch (fieldId) {
		case MainConstant.FIELD_TYPE_NAME:
		case MainConstant.FIELD_TYPE_ID:
		case MainConstant.FIELD_TYPE_TEL:
			if (fieldId == MainConstant.FIELD_TYPE_TEL) {
				fieldId = MainConstant.FIELD_TYPE_NAME;
			}
			break;
		default:
			fieldId = MainConstant.FIELD_TYPE_NAME;
		}

		return getFieldText(fieldId);
	}

	public String getSortKeyLabel() {
		return this.getIdlData().GroupTelno;
	}

	public ArrayList getChildren() {
		ArrayList list = new ArrayList();
		list.addAll(baseListModel.getGroupList());
		list.addAll(baseListModel.getUserList());
		return list;
	}

	public boolean hasChildren() {
		return baseListModel.getGroupList().size() > 0 || baseListModel.getUserList().size() > 0;
	}

	public String getTreeLabel() {
		return getLabel();
	}

	private String tongjiTreeLabel;

	public BaseListModel getListModel() {
		return baseListModel;
	}

	public int getLevel() {
		return treeLevel;
	}

	public void setLevel(int level) {
		treeLevel = level;
	}

	public List getModelSourceConnections(boolean isLocal) {
		return Collections.EMPTY_LIST;
	}

	public List getModelTargetConnections(boolean isLocal) {
		return Collections.EMPTY_LIST;
	}

	public Group getIdlData() {
		return idlData;
	}

	public void setIdlData(Group idlData) {
		this.idlData = idlData;
		if (idlData.GroupNodeFlag == 1) {
			this.physicsNodeNumber = idlData.NodeNumber;
			this.logicNodeNumber = idlData.NodeNumber;
		}
		// topoInfo
		// .setLocationAtParent(new Point(idlData.Point_x, idlData.Point_y));
		// getTopoInfo().setGeoPosition(
		// MainUtil.toGeoPosition(idlData.latitude, idlData.longitude));
	}

	public String toString() {
		return idlData.GroupName;
	}

	public String getPhysicsNodeNumber() {
		return physicsNodeNumber;
	}

	public String getLogicNodeNumber() {
		return logicNodeNumber;
	}

	/**
	 * 判断用户是否空闲状态
	 * 
	 * @return
	 */
	public boolean isStatus_Free() {
		switch (statusStruct.status) {
		case MainConstant.Status_GROUP_USER_STATUS_IDLE:
			return true;
		case MainConstant.Status_GROUP_USER_STATUS_LISTENING:
		case MainConstant.Status_GROUP_USER_STATUS_TALKING:
		case MainConstant.Status_GROUP_USER_STATUS_TEL_BUSY:
		case MainConstant.Status_GROUP_USER_STATUS_LOGOUT:
		case MainConstant.Status_GROUP_USER_STATUS_UNREACH:
		case MainConstant.Status_GROUP_USER_STATUS_NOT_EXIST:
		case MainConstant.Status_GROUP_USER_STATUS_METTING:
		case MainConstant.Status_GROUP_USER_STATUS_CALLING:
		default:
			return false;
		}
	}

	/**
	 * 判断用户是否离线不可以状态
	 * 
	 * @return
	 */
	public boolean isStatus_OffLine() {
		switch (statusStruct.status) {
		case MainConstant.Status_GROUP_USER_STATUS_LOGOUT:
		case MainConstant.Status_GROUP_USER_STATUS_UNREACH:
		case MainConstant.Status_GROUP_USER_STATUS_NOT_EXIST:
			return true;
		default:
			return false;
		}
	}

	/**
	 * 判断用户是否会议状态中
	 * 
	 * @return
	 */
	public boolean isStatus_MediaMeeting() {
		switch (statusStruct.status) {
		case MainConstant.Status_GROUP_USER_STATUS_METTING:
			return true;
		default:
			return false;
		}
	}

	private boolean isLoad = false;

	public boolean isLoad() {
		return isLoad;
	}

	public void loadGroupUser(boolean refresh) {
		loadGroupUser(refresh, false);
	}

	private long loadGroupTimeKeep = -1;

	public void loadGroupUser(boolean refresh, boolean sync) {
		/**
		 * tmpresult = DataMessageManager.getInstance().queryMediaUserList(
		 * getPhysicsNodeNumber(), getLogic_NodeNumber(),midiaUserRsp,
		 * false,false); retResult.uniteResult(tmpresult);
		 **/
		/**
		 * 发送异步请求
		 */

		// 重新加载组数据
		if (isVirType()) {
			return;
		}

		if (refresh || (!refresh && !isLoad)) {
			// wsy 取消频繁刷新,记录时间 10秒后后续刷新生效
			if (loadGroupTimeKeep > 0 && (System.currentTimeMillis() - loadGroupTimeKeep) < 10000) {
				return;
			}
			// 手工刷新,或者是未加载
			// if(getIdlData().GroupNodeFlag == 1){
			// int length = getIdlData().NodeNumber.length();
			// String p = getIdlData().NodeNumber;
			// if(length > 3){
			// p = p.substring(length -3, length);
			// }
			// DataMessageManager.getInstance().queryGroupUserList(p,
			// getIdlData().NodeNumber, this);
			// }
			// else{
			// DataMessageManager.getInstance().queryGroupUserList(getPhysicsNodeNumber(),getLogicNodeNumber(),
			// this);
			// }

			// 先将用户从组内移除,目的是使得本地缓存后, 删除的用户能够从组退出的体现
			ArrayList<MyUser> userList = this.getListModel().getUserList();
			String groupNum = getIdlData().GroupTelno;
			for (MyUser user : userList) {
				// 20160105 出现在频繁刷新时, 前一次用户刷新组返回时, 后面一次的刷新将前面刷新上来的用户的组信息清空掉,
				// 导致统计组内用户总数不正确
				// wsy 取消频繁刷新,记录时间 10秒后后续刷新生效
				user.dealToGroup(groupNum, false);
			}

//			logger.info("加载组内用户:" + getIdlData().GroupTelno);
			DataMessageManager.getInstance().queryGroupUserList(getPhysicsNodeNumber(), getLogicNodeNumber(), this, sync);

			// wsy 20181030 加载组内用户状态
			try {
				//DataMessageManager.getInstance().queryGroupUserStatus(getPhysicsNodeNumber(), getLogicNodeNumber(), getTelno());
			} catch (Exception e) {
				// TODO: handle exception
			}

			// 如果是只显示用户所在组方法 20181023 后台未实现
			// if (SettingManager.SYS.is显示调度员自身组()) {
			// DataMessageManager.getInstance().groupQueryGroupList_SubGroup_Async(getPhysicsNodeNumber(),
			// getLogicNodeNumber(), getIdlData().GroupTelno);
			// }
			isLoad = true;

			loadGroupTimeKeep = System.currentTimeMillis();
		}
	}

	/**
	 * 会话临时组,会话完毕后,需要删除的 定义组号码为 * 100 以上10位
	 * 
	 * @return
	 */
	public boolean isNeedDelGroup() {
		// 带*号的号码为临时组
		String groupNum = idlData.GroupTelno;
		try {
			for (String 临时组分隔标志 : 临时组分隔标志列表) {
				if ((groupNum.lastIndexOf(临时组分隔标志) >= 0) && (groupNum.lastIndexOf(临时组分隔标志) + 临时组分隔标志.length() + 2) == groupNum.length()) {
					return true;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return false;
	}

	// 是否虚拟组,不具有呼叫等功能
	private boolean isVirType = false;

	public boolean isVirType() {
		return isVirType;
	}

	public void setVirType(boolean isVirType) {
		this.isVirType = isVirType;
	}

	/**
	 * 是否异节点组
	 * 
	 * @return
	 */
	public boolean otherNodeGroup() {
		if (idlData.GroupNodeFlag == 1 && !"".equals(idlData.NodeNumber)) {
			return true;
		}
		return false;
	}

	public void otherNodeGroupSet(Group group) {
		idlData.NodeNumber = group.NodeNumber;
		idlData.GroupNodeFlag = group.GroupNodeFlag;

	}


	public int[] getSupportField() {
		// TODO Auto-generated method stub
		return null;
	}


	public String[] getFieldNames() {
		// TODO Auto-generated method stub
		return null;
	}
    // wsy 20190319 增加应急组判断
    public boolean isYingJiZu() {
	if (getIdlData().GroupType == 2) {
	    return true;
	}
	return false;
    }

}
